<?php

namespace Handler;

use Model\RepData;
use Workerman\Lib\Timer;
use Extension\Tools;

class TPHandler {
	/**
	 * 单例
	 *
	 * @var WMHandler
	 */
	private static $m_Instance;
	/**
	 * 后台地址
	 *
	 * @var string
	 */
	private $m_Url;
	/**
	 * 游戏ID
	 *
	 * @var integer
	 */
	private $m_GameId;
	/**
	 * 游戏名
	 *
	 * @var string
	 */
	private $m_GameName;
	/**
	 * 构造函数
	 */
	protected function __construct() {
		Timer::add ( 1, array (
				$this,
				'mb_TimerTask' 
		), array (), true );
	}
	/**
	 * 析构函数
	 */
	protected function __destruct() {
	}
	/**
	 * 获取单例
	 *
	 * @return \Handler\TPHandler
	 */
	public static function mb_GetInstance() {
		if (! (self::$m_Instance instanceof self)) {
			self::$m_Instance = new self ();
		}
		return self::$m_Instance;
	}
	/**
	 * 时间任务(每一秒执行一次)
	 */
	public function mb_TimerTask() {
	}
	/**
	 * 初始化
	 *
	 * @param unknown $url        	
	 * @param unknown $gameId        	
	 * @param unknown $gameName        	
	 */
	public function mb_Init($url, $gameId, $gameName) {
		$this->m_Url = $url . 'thinkphp/index.php/home/SFS/';
		$this->m_GameId = $gameId;
		$this->m_GameName = $gameName;
	}
	
	/**
	 * 查询
	 *
	 * @param string $name        	
	 * @return \Model\RepData
	 */
	public function mb_Query($name) {
		$url = $this->m_Url . 'mb_AccountQuery';
		for($i = 0; $i < 5; $i ++) {
			$pData = array (
					'name' => $name 
			);
			$repData = $this->mb_DecodeWMData ( $this->mb_SendPost ( $url, $pData ) );
			if ($repData->m_Result != ErrCode_Network)
				return $repData;
		}
		return $repData;
	}
	/**
	 * 保存用户数据
	 *
	 * @param string $name        	
	 * @param double $coin        	
	 * @param string $remark        	
	 * @return \Model\RepData
	 */
	public function mb_Save($name, $coin, $remark) {
		$url = $this->m_Url . 'mb_AccountSave';
		for($i = 0; $i < 5; $i ++) {
			$pData = array (
					'name' => $name,
					'coin' => $coin,
					'gameId' => $this->m_GameId,
					'remark' => $remark 
			);
			$repData = $this->mb_DecodeWMData ( $this->mb_SendPost ( $url, $pData ) );
			if ($repData->m_Result != ErrCode_Network)
				return $repData;
		}
		return $repData;
	}
	/**
	 * 推送更新用户消息（当游戏开始了，玩家强制断线退出到大厅的时候）
	 *
	 * @param string $name        	
	 * @return \Model\RepData
	 */
	public function mb_UpdateUserData($name) {
		$url = $this->m_Url . 'mb_UpdateUserDataPush';
		for($i = 0; $i < 5; $i ++) {
			$pData = array (
					'name' => $name 
			);
			$repData = $this->mb_DecodeWMData ( $this->mb_SendPost ( $url, $pData ) );
			if ($repData->m_Result != ErrCode_Network)
				return $repData;
		}
		return $repData;
	}
	// /**
	// * 发送POST数据
	// *
	// * @param unknown $url
	// * @param unknown $post_data
	// * @return string
	// */
	// private function mb_SendPost($url, $pData) {
	// $postData = json_encode ( $pData );
	// $ch = curl_init ( $url );
	// curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
	// curl_setopt ( $ch, CURLOPT_POSTFIELDS, $postData );
	// curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
	// curl_setopt ( $ch, CURLOPT_TIMEOUT, 5 );
	// curl_setopt ( $ch, CURLOPT_HTTPHEADER, array (
	// 'Content-Type: application/json',
	// 'Content-Length: ' . strlen ( $postData )
	// ) );
	// $data = curl_exec ( $ch );
	// return $data;
	// }
	
	/**
	 * 发送POST数据
	 *
	 * @param unknown $url        	
	 * @param unknown $pData        	
	 * @return string
	 */
	private function mb_SendPost($url, $pData) {
		$postdata = http_build_query ( $pData );
		// echo $url . '?' . $postdata;
		// echo "\n";
		Tools::mb_LogResult ( $url . '?' . $postdata );
		$options = array (
				'http' => array (
						'method' => 'POST',
						'header' => 'Content-type:application/x-www-form-urlencoded',
						'content' => $postdata,
						'timeout' => 15 * 60  // 超时时间（单位:s）
				) 
		);
		$context = stream_context_create ( $options );
		$result = file_get_contents ( $url, false, $context );
		return $result;
	}
	/**
	 *
	 * @param unknown $jData        	
	 * @return \Model\RepData
	 */
	private function mb_DecodeWMData($jData) {
		if ($jData == '') {
			$repData = new RepData ();
			$repData->m_Result = ErrCode_Network;
			$repData->m_Data = '外部服务器异常，请稍后再试';
			$repData->m_Sign = '';
			return $repData;
		} else {
			return json_decode ( $jData );
		}
	}
}